import { Modal, Button, DatePicker, message, Space, Divider, Select } from 'antd';
import { ExclamationCircleOutlined, PaperClipOutlined } from '@ant-design/icons';
import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import ReactJson from 'react-json-view';
import { queryDeviceLinkageRecord,removeDeviceLinkageRecord,batchRemoveDeviceLinkageRecord } from '@/services/deviceLinkageRecord';
import DetailForm from './components/DetailForm';
import { paramToStringRemovePage } from '@/utils/utils';
import styles from '../style.less'
const { confirm } = Modal;

/**
 *  删除节点
 * @param selectedRows
 */
 const handleRemove = async (fields: any) => {
  const hide = message.loading('正在删除');

  try {
    await removeDeviceLinkageRecord();
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const Log: React.FC = () => {

  const columns: ProColumns[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      search:false,
    },
    {
      title: '任务名称',
      dataIndex: 'linkageName',

    }, {
      title: '设备Id',
      dataIndex: 'deviceId',
      search:false,
    }, {
      title: '设备名称',
      dataIndex: 'deviceName',

    }, {
      title: '变量数据',
      dataIndex: 'attrValue',
      search:false,
      width:300,
      render: (attr) => (
        <Space  style={{width:'300px'}} >
           <ReactJson  style={{color:'white'}}   displayDataTypes={false} displayObjectSize={false} collapsed={true} src={JSON.parse(attr)} /> 
           {/* {attr} */}
        </Space>
      ),

    }, {
      title: '通讯指令',
      dataIndex: 'message',
      search:false,
    }, {
      title: '反馈信息',
      dataIndex: 'reserve',
      search:false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      search:false,
    },
    // {
    //   title: '更新时间',
    //   dataIndex: 'updateTime',
    //   search:false,
    // },

    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a onClick={() => {
          confirm({
            title: '您确定要删除吗?',
            icon: <ExclamationCircleOutlined />,
            async onOk() {
              await removeDeviceLinkageRecord({id:record.id});
              ref?.current?.reload();
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }}
        >
          删除
        </a>
      ],
    },
  ];
  
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [searchParams, setSearchParams] = useState({});
  const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>([]);
  const onSelectChange = async (sKeys:number[]) => {
    setSelectedRowKeys(sKeys);

  };
  
  //批量删除
  const batchRemove = async () => {
    const hide = message.loading('正在删除');
    try {
      await batchRemoveDeviceLinkageRecord({ ids: selectedRowKeys.join(',')});
      setSelectedRowKeys([]);
      hide();
      message.success('删除成功，正在刷新！');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

  const ref = useRef<ActionType>();
  return (
    <>
      <ProTable
        actionRef={ref}
        columns={columns}
        options={false}
        dateFormatter="string"
        search={{
          span: 6,
          labelWidth: 'auto',
        }}
        rowSelection={{selectedRowKeys,onChange: onSelectChange}}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <a  onClick={() => {
              confirm({
                title: '您确定要批量删除吗?',
                icon: <ExclamationCircleOutlined />,
                async onOk() {
                  await batchRemove();
                  ref.current?.reload();
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }} >批量删除</a>
           
            </Space>
          );
        }}
      //  request={(params) => queryDeviceLinkageRecord(params)}
        request={
          async ( params) => {
            console.log(params)
            setSearchParams(params);
            return  await  queryDeviceLinkageRecord({ ...params})  }}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
        }}
        headerTitle=""
        toolBarRender={() => [
          <a href={"/api/exportDeviceLinkageRecordExcel?"+paramToStringRemovePage(searchParams)}>
            <Button key="out" className={styles.exportBtn} >
               <PaperClipOutlined /> 导出数据
            </Button>
          </a>
          
        ]}
      />
      {formValues && Object.keys(formValues).length ? (
        <DetailForm
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
        />
      ) : null}
    </>
  );
};

export default Log;